<template>
  <div class="image-upload-container">
    <h2>上传房源图片 - 房屋ID: {{ houseId }}</h2>

    <div class="upload-area">
      <input
          type="file"
          multiple
          accept="image/*"
          @change="handleFileChange"
      >
      <button @click="uploadImages" class="upload-btn">上传图片</button>
    </div>

    <div class="preview-area" v-if="previewImages.length">
      <h3>预览图片</h3>
      <div class="image-grid">
        <div v-for="(image, index) in previewImages" :key="index" class="image-item">
          <img :src="image.preview" alt="房源图片">
          <div class="image-actions">
            <label class="cover-checkbox">
              <input
                  type="checkbox"
                  v-model="image.iscover"
                  @click="setAsCover(index)"
              >
              设为封面
            </label>
            <button @click="removeImage(index)" class="remove-btn">删除</button>
          </div>
        </div>
      </div>
    </div>

    <button @click="finishUpload" class="finish-btn">完成</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import common_util from "../../util/common_util.js";

const ErrorCode = {
  SUCCESS: { code: 0, msg: '成功' },
  USER_TOKEN_INVALID: { code: 401, msg: '用户token无效' },
  PARAM_MISSING: { code: 400, msg: '参数缺失' },
  SERVER_ERROR: { code: 500, msg: '服务器错误' }
}

const route = useRoute()
const router = useRouter()
const houseId = ref(route.params.houseId)
const selectedFiles = ref([])
const previewImages = ref([])
const isUploading = ref(false)

onMounted(() => {
  if (!houseId.value) {
    ElMessage.error('缺少房屋ID参数')
    router.push({ name: 'my-houses' })
  }
})

const handleFileChange = (event) => {
  const files = Array.from(event.target.files)
  selectedFiles.value = files
  previewImages.value = files.map((file, index) => ({
    file,
    preview: URL.createObjectURL(file),
    is_cover: index === 0, // 使用与后端一致的字段名
    index
  }))
}

const setAsCover = (index) => {
  previewImages.value.forEach((img, i) => {
    img.is_cover = i === index
  })
}

const removeImage = (index) => {
  const wasCover = previewImages.value[index].is_cover
  previewImages.value.splice(index, 1)
  selectedFiles.value.splice(index, 1)

  if (wasCover && previewImages.value.length > 0) {
    previewImages.value[0].is_cover = true
  }
}

const uploadImages = async () => {
  if (!selectedFiles.value.length) {
    ElMessage.warning('请选择至少一张图片')
    return
  }

  isUploading.value = true

  try {
    // 由于后端API只支持单张上传，我们需要逐个上传
    for (let i = 0; i < selectedFiles.value.length; i++) {
      const file = selectedFiles.value[i]
      const is_cover = previewImages.value[i].is_cover

      const formData = new FormData()
      formData.append('file', file)
      formData.append('house_id', houseId.value)
      formData.append('is_cover', is_cover) // 使用与后端一致的字段名

      const headers = common_util.accessHeader()
      delete headers['Content-Type'] // 让浏览器自动设置Content-Type

      const response = await axios.post('/api/house-images', formData, { headers })

      if (response.data.code !== ErrorCode.SUCCESS.code) {
        throw new Error(response.data.msg || '上传失败')
      }
    }

    ElMessage.success('所有图片上传成功!')
    selectedFiles.value = []
    previewImages.value = []
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error.message || '上传失败，请重试')
  } finally {
    isUploading.value = false
  }
}

const finishUpload = () => {
  router.push({ name: 'my-houses' })
}
</script>

<style scoped>
.image-upload-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.upload-area {
  margin: 20px 0;
  padding: 20px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  text-align: center;
}

.upload-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.preview-area {
  margin-top: 30px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.image-item {
  position: relative;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cover-checkbox {
  color: white;
  font-size: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.cover-checkbox input {
  margin-right: 5px;
}

.remove-btn {
  padding: 3px 8px;
  background-color: #ff4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.finish-btn {
  display: block;
  margin: 20px auto;
  padding: 10px 30px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}
</style>